/**
 * Created by gm on 2016/7/21.
 */
/**
 * New node file
 */
var http = require('http');
var crypto = require('crypto');
var urlencode = require('urlencode');

var monk=require('monk');
var db=monk('localhost:27017/usercollection');
var mescollection=db.get('messagecollection');

Date.prototype.Format = function (fmt) { //author: meizz
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

exports.sendContent=function(data){
    var date=new Date();
    var mobile=data.mobile;
    var content=urlencode(data.content);
    //匹配%20转为+
    var re1=/%20/g;
    var content1=content.replace(re1,"+");
    //匹配(转为%28
    var re2=/\(/g;
    var content2=content1.replace(re2,"%28");
    //匹配)转为%29
    var re3=/\)/g;
    var content3=content2.replace(re3,"%29");
    //匹配~转为%7E
    var re4=/\~/g;
    var content4=content3.replace(re4,"%7E");
    //匹配'转为%27
    var re5=/\'/g;
    var content5=content4.replace(re5,"%27");
    //匹配*转为%2A
    var re6=/\*/g;
    var content6=content5.replace(re6,"%2A");
    //匹配!转为%21
    var re7=/!/g;
    var cont=content6.replace(re7,"%21");
    var md5Str = '9e3f6b'+mobile+cont;
    var md5 = crypto.createHash('md5');
    md5.update(md5Str);
    var d = md5.digest('hex');
    var postParams = 'sn=213254078878284&content='+cont+'&mobiles='+mobile+'&code='+d+'&extno=100064';
    var options = {
        hostname: 'api01.wangjinxintong.com',
        port: 8090,
        path: '/smsg/p/send',
        method: 'post',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        }
    };
    var req = http.request(options,function(res){
        console.log('STATUS: ' + res.statusCode);
        console.log('HEADERS: ' + JSON.stringify(res.headers));
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
            var obj=JSON.parse(chunk);
            mescollection.insert({appId:data.appId,content:data.content,mobile:data.mobile,code:data.code,taskId:obj.taskId,status:-1,msg:obj.msg,sendTime:date.Format('yyyy-MM-dd hh:mm:ss.S')},
                function(err,data){
                    if(err) throw err;
                    res.json(data);
                }
            );
        });
    });
    req.on('error', function (e) {
        console.log('problem with request: ' + e.message);
    });
    req.write(postParams);
    req.end();
};
